package com.illtamer.infinite.sillage.util;

import org.commonmark.Extension;
import org.commonmark.ext.gfm.tables.TableBlock;
import org.commonmark.ext.gfm.tables.TablesExtension;
import org.commonmark.ext.heading.anchor.HeadingAnchorExtension;
import org.commonmark.node.Image;
import org.commonmark.node.Link;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.AttributeProvider;
import org.commonmark.renderer.html.HtmlRenderer;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MarkdownUtil {

    /**
     * 基础转化
     * */
    public static String markdownToHtml(String markdown) {
        Parser parser = Parser.builder().build();
        Node document = parser.parse(markdown);
        HtmlRenderer renderer = HtmlRenderer.builder().build();
        return renderer.render(document);
    }

    /**
     * 拓展转化
     * */
    public static String markdownToHtmlExt(String markdown) {
        // heading 自动生成 id
        Set<Extension> headingExtensions = Collections.singleton(HeadingAnchorExtension.create());
        // table: markdown -> html
        List<Extension> tableExtensions = Collections.singletonList(TablesExtension.create());
        Parser parser = Parser.builder()
                .extensions(tableExtensions)
                .build();
        Node document = parser.parse(markdown);
        HtmlRenderer renderer = HtmlRenderer.builder()
                .extensions(headingExtensions)
                .extensions(tableExtensions)
                .attributeProviderFactory((context) -> new CustomAttributeProvider())
                .build();
        return renderer.render(document);
    }

    /**
     * 自定义标签属性处理
     * */
    private static class CustomAttributeProvider implements AttributeProvider {

        @Override
        public void setAttributes(Node node, String s, Map<String, String> attributes) {
            if (node instanceof Link) {
                attributes.put("target", "_blank");
            } else if (node instanceof TableBlock) {
                attributes.put("class", "table table-bordered");
            } else if (node instanceof Image) {
                attributes.put("class", "display-inherit");
            }
        }

    }

}
